/*
  Vue.use() 插件安装
  Vue.use({}/function,options)
  {
    install(Vue,options){
      .....
    }
  }
  function(Vue,options){
    .....
  }
*/
// import Vue from 'vue'
// v-指令名:属性名.修饰符="值"
import employeesData from '@/api/constant/employees'
import store from '@/store'
function fn(dom, obj) {
  const findItem = employeesData[obj.arg].find(
    (item) => +item.id === +obj.value
  )
  dom.innerText = findItem ? '指令:' + findItem.value : '-'
}
let outFn = () => {}
export default {
  install(Vue) {
    Vue.directive('imgerror', {
      inserted(dom, obj) {
        // dom有图片就使用它的图片，没有就使用指令的值，指令没值就使用默认图片
        dom.src = dom.src || obj.value || require('@/assets/common/head.jpg')
        // 监听图片的加载出错
        dom.addEventListener('error', () => {
          dom.src = obj.value || require('@/assets/common/head.jpg')
        })
      },
      componentUpdated(dom, obj) {
        dom.src = dom.src || obj.value || require('@/assets/common/head.jpg')
      }
    })
    // 数据转换
    Vue.directive('formatnum', {
      inserted(dom, obj, vnode) {
        fn(dom, obj)
      },
      componentUpdated(dom, obj, vnode) {
        fn(dom, obj)
      }
    })
    // 点击盒子外执行一个事件
    Vue.directive('clickout', {
      inserted(dom, obj, vnode) {
        outFn = (e) => {
          // 点击的dom  e.target
          //  盒子dom  dom
          console.log('document')
          if (!dom.contains(e.target)) {
            obj.value()
          }
        }
        document.addEventListener('click', outFn)
      },
      unbind() {
        document.removeEventListener('click', outFn)
      }
    })
    // 指令解决按钮是否显示
    Vue.directive('buttonshow', {
      inserted(dom, obj) {
        if (
          store.state.user.userInfo.roles &&
          !store.state.user.userInfo.roles.points.includes(obj.value)
        ) {
          dom.style.display = 'none'
        }
      },
      componentUpdated(dom, obj) {
        if (
          store.state.user.userInfo.roles &&
          !store.state.user.userInfo.roles.points.includes(obj.value)
        ) {
          dom.style.display = 'none'
        }
      }
    })
  }
}
